import { Injectable } from '@nestjs/common';
import { UserAdmin_Service } from '../userAdmin/userAdmin.service';
import { AuthAdmin_SignIn_Dto } from './assets/authAdmin.dto';
import * as argon2 from 'argon2';
import { JwtService } from '@nestjs/jwt';
import { Constant_Enum_Enum_UserAdmin_Status } from '@/common/constants/enum';
import { Class_HttpException_Base } from '@/common/classes/httpException';
import { UserAdmin_Return_RePreClass } from '../userAdmin/assets/userAdmin.class';
import { IUserAdmin_JwtStrategyPayload } from '@/common/typeScripts/index';

@Injectable()
export class AuthAdmin_Service {
  constructor(
    private userAdmin_Service: UserAdmin_Service,
    private jwtService: JwtService,
  ) {}

  async authAdmin_SignIn(body: AuthAdmin_SignIn_Dto) {
    const userAdmin = await this.userAdmin_Service.userAdmin_FindOneByQuery({
      userName: body.userName,
    });
    if (!userAdmin) throw new Class_HttpException_Base('用户名或密码错误');
    if (userAdmin.statusUser == Constant_Enum_Enum_UserAdmin_Status.UserAdmin_Status_Disable) {
      throw new Class_HttpException_Base('用户已被拉黑');
    }
    const pass = await argon2.verify(userAdmin.password, body.password);
    if (!pass) throw new Class_HttpException_Base('用户名或密码错误');
    const payload: IUserAdmin_JwtStrategyPayload = {
      userId: userAdmin.id,
      userName: userAdmin.userName,
      statusUser: userAdmin.statusUser,
      type: 'adm',
    };
    return {
      userAdmin: {
        id: userAdmin.id,
        userName: userAdmin.userName,
        avatar: userAdmin.avatar,
        roleId: userAdmin.role.id,
        roleName: userAdmin.role.roleName,
      } as UserAdmin_Return_RePreClass,
      token: await this.jwtService.signAsync(payload),
    };
  }
}
